//
//  HMUserAccountViewModel.swift
//  webo
//
//  Created by apple on 2016/11/15.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

/*
 1.封装数据逻辑处理
 2.封装网络请求
 3.封装数据缓存
 */

let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userInfo.plist")

class HMUserAccountViewModel: NSObject {
    
    var userAccount: HMUserAccount?
    
    var access_token: String? {
        return userAccount?.access_token
    }
//    var headURL: URL? {
//        return URL(string: userAccount?.avatar_large ?? "")
//    }

    var headUrl: URL?{
    return URL(string: userAccount?.avatar_large ?? "")
    }
    static let shared:HMUserAccountViewModel = HMUserAccountViewModel()
    
    override init() {
        super.init()
        self.userAccount = self.loadUserAccount()
    }

    var isexpires:Bool {
        if userAccount?.expires_date?.compare(Date()) == ComparisonResult.orderedDescending {
//            print(userAccount?.expires_date)
            return true
        }
    return false
    }

    var userLogin: Bool {
        if userAccount?.access_token != nil && isexpires == true{
        return true
        }
        return false
    }
    
    
    
    func loadAccuessTocken(code: String,finished: @escaping (Bool) -> ()){
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        let parameter = ["client_id":client_id,
                         "client_secret":client_secret,
                         "grant_type":"authorization_code",
                         "code":code,
                         "redirect_uri":redirect_uri]
        
        HMNetworkingTools.shared.request(method: .POST, urlString: urlstring, parameter: parameter, finishedBlock: {(responseObject,error) -> () in
            //成功
            if error != nil{
            finished(false)
                return
            }
          self.loadUserInfo(dict: responseObject as! [String : Any],loadInfoFinished:finished)
        })
    }
    
    func loadUserInfo(dict: [String : Any],loadInfoFinished: @escaping (Bool) -> () ){
        let urlstring = "https://api.weibo.com/2/users/show.json"
        let token = dict["access_token"]
        let uid = dict["uid"]
        let parameter = ["access_token":token,"uid":uid]
        
        
        HMNetworkingTools.shared.request(method: .GET, urlString: urlstring, parameter: parameter) {(responseObject,error) -> () in
            if error != nil{
                loadInfoFinished(false)
                return
            }
            
//            print(responseObject)
            var userInfoDic = responseObject as! [String : Any]
            for (key,value) in dict{
            userInfoDic[key] = value
            }
            
            //字典转模型
            let userAccount = HMUserAccount(dict: userInfoDic)
            self.saveUserInfo(usAccount: userAccount)
           
            //赋值
            self.userAccount = userAccount

            loadInfoFinished(true)
        }

    }
    
    
    
//    存档
   private func saveUserInfo(usAccount: HMUserAccount){
        
        NSKeyedArchiver.archiveRootObject(usAccount, toFile: path)
        print(path)
    }
//    读取数据
    func loadUserAccount() -> HMUserAccount?{
        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        if let userAccount = account as? HMUserAccount {
            return userAccount
        }
        return nil
    }
}
